# -*- coding: utf-8 -*-

import os

import re
import chardet
from django import forms
from django.template.loader import render_to_string
from EINAdiyno.Email import Email
from export.exportCatalog import ExportCatalog
from settings import db, STATICFILES_DIRS, EMAIL_HOST_PASSWORD, EMAIL_HOST_USER, EMAIL_PORT, EMAIL_HOST


class UploadCatalog(forms.Form):
    file = forms.FileField()
    type = forms.ChoiceField(widget=forms.Select, choices=((1, 'экспорт продуктов от поставщика'),
                                                           (2, 'обновить позиции цен'), (3, 'прайс МТІ'),
                                                           (4, 'прайс Юг-Контракт'), (5, 'прайс Стек')), initial='1',
                             required=True, label='Действие:')
    delimetr = forms.CharField(label='Разделитель', max_length=1, widget=forms.TextInput(attrs={'size': 1}),
                               required=False)

    def getFileContent(self):
        file = self.files['file']
        content = ''

        for chunk in file.chunks():
            content += chunk.decode(chardet.detect(chunk)['encoding'], 'ignore').encode('utf-8', 'ignore')
        return content

    def getMtiSKU(self):
        delimitr = self.data['delimetr'].encode('utf-8')
        if not delimitr:
            delimitr = ','
        content = self.getFileContent().replace('\r', '')
        rows = content.split('\n')
        listOfSku = []
        for row in rows[3:]:
            cells = row.split(delimitr)
            try:
                cell = cells[3].replace(' ', '').replace('\"', '').replace('\'', '')
                if cell:
                    listOfSku.append(cell)
            except IndexError:
                pass
        return listOfSku

    def getUgSKU(self):
        content = self.getFileContent().replace('\r', '')
        rows = content.split('\n')
        listOfSku = []
        for row in rows[1:]:
            cells = row.split(',')
            try:
                cell = cells[3].replace(' ', '').replace('\"', '').replace('\'', '')
                if cell:
                    listOfSku.append(cell)
            except IndexError:
                pass
        return listOfSku

    def getProduct(self):
        return ExportCatalog(self.getFileContent(), self.data['type'], self.data['delimetr']).products


def transliterate(string):
    capital_letters = {u'А': u'A',
                       u'Б': u'B',
                       u'В': u'V',
                       u'Г': u'G',
                       u'Д': u'D',
                       u'Е': u'E',
                       u'Ё': u'E',
                       u'З': u'Z',
                       u'И': u'I',
                       u'Й': u'Y',
                       u'К': u'K',
                       u'Л': u'L',
                       u'М': u'M',
                       u'Н': u'N',
                       u'О': u'O',
                       u'П': u'P',
                       u'Р': u'R',
                       u'С': u'S',
                       u'Т': u'T',
                       u'У': u'U',
                       u'Ф': u'F',
                       u'Х': u'H',
                       u'Ъ': u'',
                       u'Ы': u'Y',
                       u'Ь': u'',
                       u'Э': u'E', }

    capital_letters_transliterated_to_multiple_letters = {u'Ж': u'Zh',
                                                          u'Ц': u'Ts',
                                                          u'Ч': u'Ch',
                                                          u'Ш': u'Sh',
                                                          u'Щ': u'Sch',
                                                          u'Ю': u'Yu',
                                                          u'Я': u'Ya', }

    lower_case_letters = {u'а': u'a',
                          u'б': u'b',
                          u'в': u'v',
                          u'г': u'g',
                          u'д': u'd',
                          u'е': u'e',
                          u'ё': u'e',
                          u'ж': u'zh',
                          u'з': u'z',
                          u'и': u'i',
                          u'й': u'y',
                          u'к': u'k',
                          u'л': u'l',
                          u'м': u'm',
                          u'н': u'n',
                          u'о': u'o',
                          u'п': u'p',
                          u'р': u'r',
                          u'с': u's',
                          u'т': u't',
                          u'у': u'u',
                          u'ф': u'f',
                          u'х': u'h',
                          u'ц': u'ts',
                          u'ч': u'ch',
                          u'ш': u'sh',
                          u'щ': u'sch',
                          u'ъ': u'',
                          u'ы': u'y',
                          u'ь': u'',
                          u'э': u'e',
                          u'ю': u'yu',
                          u'я': u'ya', }

    for cyrillic_string, latin_string in capital_letters_transliterated_to_multiple_letters.iteritems():
        string = re.sub(ur"%s([а-я])" % cyrillic_string, ur'%s\1' % latin_string, string)

    for dictionary in (capital_letters, lower_case_letters):

        for cyrillic_string, latin_string in dictionary.iteritems():
            string = string.replace(cyrillic_string, latin_string)

    for cyrillic_string, latin_string in capital_letters_transliterated_to_multiple_letters.iteritems():
        string = string.replace(cyrillic_string, latin_string.upper())

    return string


class UpdateImage():
    def __init__(self, path=None):
        if path:
            self.path = path
        else:
            self.path = os.path.join(STATICFILES_DIRS[0], 'product')
        self.setImage()

    def getAttributeMedia(self):
        var = db.sqlQuery('SELECT attribute_id FROM firsteav_attribute where attribute_code=\'media_gallery\';')
        return var[0][0]

    def getAllProductId(self):
        var = db.sqlQuery('SELECT entity_id, sku FROM firstcatalog_product_entity where entity_type_id=4;')
        return var

    def setImage(self):
        mediaId = self.getAttributeMedia()
        products = self.getAllProductId()
        for j in range(len(products) - 1):
            product = products[len(products) - j - 1]
            try:
                sku = product[1].replace('/', "")
                if os.path.exists(path=self.path + '/' + sku[0] + '/' + sku[1]):
                    dirList = os.listdir(self.path + '/' + sku[0] + '/' + sku[1])
                    for dir in dirList:
                        var = dir.split('_')
                        if len(var) > 2:
                            dir_ = ''
                            for i in range(len(var) - 2):
                                dir_ += var[i]
                        else:
                            dir_ = var[0]

                        if sku == dir_:
                            number = dir.split('_')
                            number = int(number[len(number) - 1].split('.')[0]) + 1
                            self.addProductImage(product[0], mediaId, '%s/%s/%s' % (dir[0], dir[1], dir), number)
            except IndexError:
                pass
            db.commit()

    def addProductImage(self, productId, mediaId, image, number):
        var = db.sqlQuery(
            '''SELECT * FROM firstcatalog_product_entity_media_gallery where value='%s';''' % image)
        if not var:
            db.sqlQuery('''INSERT INTO firstcatalog_product_entity_media_gallery (`attribute_id`, `entity_id`, `value`)
                VALUES ('%s', '%s', '%s');''' % (mediaId, productId, image))
            var = db.sqlQuery(
                '''SELECT * FROM firstcatalog_product_entity_media_gallery where value='%s';''' % image)
            db.sqlQuery('''INSERT INTO firstcatalog_product_entity_media_gallery_value (`value_id`, `store_id`, `position`,
                `disabled`) VALUES ('%s', '0', '%s', '0');''' % (var[0][0], number))


def sendReport(html, recipient, subject):
    email = Email(EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD)
    email.login()
    email.sendMsg(recipient, subject, html)


